package blackstar.plugin.monitor.jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.management.ObjectName;

import blackstar.agent.jvm.JMXProxy;
import blackstar.plugin.monitor.AbstractMonitor;

/**
 * @author Ray (ayufox@gmail.com)
 */
public class MemoryMonitor extends AbstractMonitor
{
	private Map<String, MemoryPoolMXBean> memoryPoolMXBeans = new HashMap<String, MemoryPoolMXBean>();

	private Map<String, String> nameMap = new HashMap<String, String>();
	{
		nameMap.put("Tenured", "TenuredSpace");
		nameMap.put("Old", "TenuredSpace");
		nameMap.put("Perm", "PermSpace");
	}

	public MemoryMonitor()
	{
		super("memory");
	}

	public MemoryMonitor(Map<String, String> nameMap)
	{
		super();
		this.nameMap.clear();
		this.nameMap.putAll(nameMap);
	}
	
	protected void doInit(JMXProxy jmxProxy) throws Exception
	{
		try
		{
			ObjectName objectName = new ObjectName(
					"java.lang:type=MemoryPool,*");
			Set<ObjectName> set = jmxProxy.getLocalMBeanServerConnection()
					.queryNames(objectName, null);
			for (ObjectName on : set)
			{
				for (Map.Entry<String, String> entry : nameMap.entrySet())
				{
					if (on.toString().contains(entry.getKey()))
					{
						MemoryPoolMXBean memoryPoolMXBean = ManagementFactory
								.newPlatformMXBeanProxy(jmxProxy
										.getLocalMBeanServerConnection(), on
										.toString(), MemoryPoolMXBean.class);

						memoryPoolMXBeans.put(entry.getValue(),
								memoryPoolMXBean);

						memoryPoolMXBean = null;
						break;
					}
				}
			}
		} catch (Exception e)
		{
			LOGGER.info("Init Failed:" + e.getMessage());
		}
	}

	protected void doOnTimeout() throws Exception
	{
		for (Map.Entry<String, MemoryPoolMXBean> entry : memoryPoolMXBeans
				.entrySet())
		{
			long data = entry.getValue().getUsage().getUsed() / (1024 * 1024); 
			report(entry.getKey(), data);
		}
	}

}
